/**
 * 采购订单 - 新增或编辑界面
 * 
 * @author linbo
 */
Ext.define("PSI.BillRelation.POBillChoiceForm", {
	extend : "Ext.window.Window",
	config : {
		parentForm : null,
		entity : null
	},

	/**
	 * 初始化组件
	 */
	initComponent : function() {
		var me = this;
		me.__readOnly = false;
		var entity = me.getEntity();
		this.adding = entity == null;

		Ext.apply(me, {
			title : "关联采购订单",
			modal : true,
			onEsc : Ext.emptyFn,
            autoScroll: true,
			// maximized : true,
			width : 740,
			height : 480,
			layout : "border",
			// defaultFocus : "editSupplier",
			tbar : ["-", {
						text : "选择",
						id : "pcf_buttonSave",
						iconCls : "PSI-button-ok",
						handler : me.onOK,
						scope : me
					}, "-", {
						text : "取消",
						id : "pcf_buttonCancel",
						iconCls : "PSI-button-cancel",
						handler : function() {
							if (me.__readonly) {
								me.close();
								return;
							}
							PSI.MsgBox.confirm("请确认是否取消当前操作？", function() {
                                me.close();
                            });
						},
						scope : me
					}],
			items : [
						{
							region : "north",
							height : 120,
							width : 620,
							// layout : "fit",
							border : 0,
							title : "查询条件",
							collapsible : true,
							layout : {
								type : "table",
								columns : 3
							},
							items : me.getQueryCmp()
						},
						{
							region : "center",
							layout : "fit",
							border : 0,
							items : [me.getMainGrid()]
						}
					],
			listeners : {
				show : {
					fn : me.onWndShow,
					scope : me
				},
				close : {
					fn : me.onWndClose,
					scope : me
				}
			}
		});

		me.callParent(arguments);

		me.__editorList = [];

		me.refreshMainGrid();
	},

	onWindowBeforeUnload : function(e) {
		return (window.event.returnValue = e.returnValue = '确认离开当前页面？');
	},

	onWndClose : function() {
		Ext.get(window).un('beforeunload', this.onWindowBeforeUnload);
		this.parentForm.refreshMainGrid();
	},

	onWndShow : function() {
		Ext.get(window).on('beforeunload', this.onWindowBeforeUnload);

        var me = this;
        if(me.entity !=null){
        }

	},

	onOK : function() {
		var me = this;
        var select = me.getMainGrid().getSelectionModel().getSelection();

        if(select && select.length > 0){
        }else{
            PSI.MsgBox.showInfo("请先选择需要关联的销售订单");
            return;
        }

		Ext.getBody().mask("正在保存中...");
		Ext.Ajax.request({
			url : PSI.Const.BASE_URL + "Home/BillRelation/addRSOBillPurchase",
			method : "POST",
			params : {
				jsonStr : me.getSaveData()
			},
			callback : function(options, success, response) {
				Ext.getBody().unmask();

				if (success) {
					var data = Ext.JSON.decode(response.responseText);
					if (data.success) {
						PSI.MsgBox.showInfo("成功保存数据", function() {
									me.close();
									me.getParentForm().refreshMainGrid(data.id);
								});
					} else {
						PSI.MsgBox.showInfo(data.msg);
					}
				}
			}
		});

	},
    getSaveData : function() {
        var me = this;

		var select = me.getMainGrid().getSelectionModel().getSelection();

        if(select && select.length > 0){
            var result = {
                relation_id : me.entity.data.id,
                bill_id : select[0].get("id")
            };
        }else{
            PSI.MsgBox.showInfo("请先选择需要关联的销售订单");
        }

        return Ext.JSON.encode(result);
    },
    /**
     * 销售订单主表
     */
    getMainGrid : function() {
        var me = this;
        if (me.__mainGrid) {
            return me.__mainGrid;
        }

        var modelName = "PSISOBill";
        Ext.define(modelName, {
            extend : "Ext.data.Model",
            fields : ["id", "ref", "billType","supplierName", "contact", "tel",
                "fax", "inputUserName", "bizUserName",
                "billStatus", "goodsMoney", "dateCreated",
                "paymentType", "tax", "moneyWithTax", "dealDate",
                "dealAddress", "orgName", "confirmUserName",
                "confirmDate", "billMemo"]
        });
        var store = Ext.create("Ext.data.Store", {
            autoLoad : false,
            model : modelName,
            data : [],
            pageSize : 20,
            proxy : {
                type : "ajax",
                actionMethods : {
                    read : "POST"
                },
                url : PSI.Const.BASE_URL + "Home/BillRelation/rpoEditBillList",
                reader : {
                    root : 'dataList',
                    totalProperty : 'totalCount'
                }
            }
        });
        store.on("beforeload", function() {
            store.proxy.extraParams = me.getQueryParam();
        });
        store.on("load", function(e, records, successful) {
            if (successful) {
                me.gotoMainGridRecord(me.__lastId);
            }
        });

        me.__mainGrid = Ext.create("Ext.grid.Panel", {
            viewConfig : {
                enableTextSelection : true
            },
            border : 0,
            columnLines : true,
            columns : [{
                xtype : "rownumberer",
                width : 50
            }, {
                header : "状态",
                dataIndex : "billStatus",
                menuDisabled : true,
                sortable : false,
                width : 60,
                renderer : function(value) {
                    if (value == 0) {
                        return "<span style='color:red'>待审核</span>";
                    } else if (value == 1000) {
                        return "已审核";
                    } else {
                        return "";
                    }
                }
            }, {
                header : "采购订单号",
                dataIndex : "ref",
                width : 110,
                menuDisabled : true,
                sortable : false
            }, {
                header : "订单类型",
                dataIndex : "billType",
                menuDisabled : true,
                sortable : false
            }, {
                header : "交货日期",
                dataIndex : "dealDate",
                menuDisabled : true,
                sortable : false
            }, {
                header : "交货地址",
                dataIndex : "dealAddress",
                menuDisabled : true,
                sortable : false
            }, {
                header : "供应商",
                dataIndex : "supplierName",
                width : 300,
                menuDisabled : true,
                sortable : false
            }, {
                header : "供应商联系人",
                dataIndex : "contact",
                menuDisabled : true,
                sortable : false
            }, {
                header : "供应商电话",
                dataIndex : "tel",
                menuDisabled : true,
                sortable : false
            }, {
                header : "供应商传真",
                dataIndex : "fax",
                menuDisabled : true,
                sortable : false
            }, {
                header : "采购金额",
                dataIndex : "goodsMoney",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                width : 150
            }, {
                header : "税金",
                dataIndex : "tax",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                width : 150
            }, {
                header : "价税合计",
                dataIndex : "moneyWithTax",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                width : 150
            }, {
                header : "付款方式",
                dataIndex : "paymentType",
                menuDisabled : true,
                sortable : false,
                width : 100,
                renderer : function(value) {
                    if (value == 0) {
                        return "记应付账款";
                    } else if (value == 1) {
                        return "现金付款";
                    } else if (value == 2) {
                        return "预付款";
                    } else {
                        return "";
                    }
                }
            }, {
                header : "业务员",
                dataIndex : "bizUserName",
                menuDisabled : true,
                sortable : false
            }, {
                header : "组织机构",
                dataIndex : "orgName",
                menuDisabled : true,
                sortable : false
            }, {
                header : "制单人",
                dataIndex : "inputUserName",
                menuDisabled : true,
                sortable : false
            }, {
                header : "制单时间",
                dataIndex : "dateCreated",
                menuDisabled : true,
                sortable : false,
                width : 140
            }, {
                header : "审核人",
                dataIndex : "confirmUserName",
                menuDisabled : true,
                sortable : false
            }, {
                header : "审核时间",
                dataIndex : "confirmDate",
                menuDisabled : true,
                sortable : false,
                width : 140
            }, {
                header : "备注",
                dataIndex : "billMemo",
                menuDisabled : true,
                sortable : false
            }],
            store : store,
            tbar : [{
                id : "rso_edit_pagingToobar",
                xtype : "pagingtoolbar",
                border : 0,
                store : store
            }, "-", {
                xtype : "displayfield",
                value : "每页显示"
            }, {
                id : "rso_edit_comboCountPerPage",
                xtype : "combobox",
                editable : false,
                width : 60,
                store : Ext.create("Ext.data.ArrayStore", {
                    fields : ["text"],
                    data : [["20"], ["50"], ["100"],
                        ["300"], ["1000"]]
                }),
                value : 20,
                listeners : {
                    change : {
                        fn : function() {
                            store.pageSize = Ext
                                .getCmp("rso_edit_comboCountPerPage")
                                .getValue();
                            store.currentPage = 1;
                            Ext.getCmp("rso_edit_pagingToobar")
                                .doRefresh();
                        },
                        scope : me
                    }
                }
            }, {
                xtype : "displayfield",
                value : "条记录"
            }],
            listeners : {
                select : {
                    fn : me.onMainGridSelect,
                    scope : me
                },
                itemdblclick : {
                    fn : me.onOK,
                    scope : me
                }
            }
        });

        return me.__mainGrid;
    },
    onMainGridSelect : function() {
        var me = this;
        var item = me.getMainGrid().getSelectionModel().getSelection();
        if (item == null || item.length != 1) {

            return;
        }
        var bill = item[0];

    },
    /**
     * 查询
     */
    onQuery : function() {
        this.refreshMainGrid();
    },

    /**
     * 清除查询条件
     */
    onClearQuery : function() {
        var me = this;

        Ext.getCmp("pcf_editQueryBillStatus").setValue(-1);
        Ext.getCmp("pcf_editQueryRef").setValue(null);
        Ext.getCmp("pcf_editQueryFromDT").setValue(null);
        Ext.getCmp("pcf_editQueryToDT").setValue(null);
        Ext.getCmp("pcf_editQuerySupplier").clearIdValue();
        Ext.getCmp("pcf_editQueryPaymentType").setValue(-1);

        me.onQuery();
    },

    getQueryParam : function() {
        var me = this;

        var result = {
            billStatus : Ext.getCmp("pcf_editQueryBillStatus").getValue()
        };

        var ref = Ext.getCmp("pcf_editQueryRef").getValue();
        if (ref) {
            result.ref = ref;
        }

        var supplierId = Ext.getCmp("pcf_editQuerySupplier").getIdValue();
        if (supplierId) {
            result.supplierId = supplierId;
        }

        var fromDT = Ext.getCmp("pcf_editQueryFromDT").getValue();
        if (fromDT) {
            result.fromDT = Ext.Date.format(fromDT, "Y-m-d");
        }

        var toDT = Ext.getCmp("pcf_editQueryToDT").getValue();
        if (toDT) {
            result.toDT = Ext.Date.format(toDT, "Y-m-d");
        }

        var paymentType = Ext.getCmp("pcf_editQueryPaymentType").getValue();
        result.paymentType = paymentType;

        return result;
    },
    gotoMainGridRecord : function(id) {
        var me = this;
        var grid = me.getMainGrid();
        grid.getSelectionModel().deselectAll();
        var store = grid.getStore();
        if (id) {
            var r = store.findExact("id", id);
            if (r != -1) {
                grid.getSelectionModel().select(r);
            } else {
                grid.getSelectionModel().select(0);
            }
        } else {
            grid.getSelectionModel().select(0);
        }
    },
    /**
     * 查询条件
     */
    getQueryCmp : function() {
        var me = this;
        return [{
            id : "pcf_editQueryBillStatus",
            xtype : "combo",
            queryMode : "local",
            editable : false,
            valueField : "id",
            labelWidth : 60,
            labelAlign : "right",
            labelSeparator : "",
            fieldLabel : "状态",
            margin : "5, 0, 0, 0",
            store : Ext.create("Ext.data.ArrayStore", {
                fields : ["id", "text"],
                data : [[-1, "全部"], [0, "待审核"], [1000, "已审核"]]
            }),
            value : -1
        }, {
            id : "pcf_editQueryRef",
            labelWidth : 60,
            labelAlign : "right",
            labelSeparator : "",
            fieldLabel : "单号",
            margin : "5, 0, 0, 0",
            xtype : "textfield"
        }, {
            id : "pcf_editQueryFromDT",
            xtype : "datefield",
            margin : "5, 0, 0, 0",
            format : "Y-m-d",
            labelAlign : "right",
            labelSeparator : "",
            fieldLabel : "交货日期（起）"
        }, {
            id : "pcf_editQueryToDT",
            xtype : "datefield",
            margin : "5, 0, 0, 0",
            format : "Y-m-d",
            labelAlign : "right",
            labelSeparator : "",
            fieldLabel : "交货日期（止）"
        }, {
            id : "pcf_editQuerySupplier",
            xtype : "psi_supplierfield",
            parentCmp : me,
            labelAlign : "right",
            labelSeparator : "",
            labelWidth : 60,
            margin : "5, 0, 0, 0",
            fieldLabel : "供应商"
        }, {
            id : "pcf_editQueryPaymentType",
            labelAlign : "right",
            labelSeparator : "",
            fieldLabel : "付款方式",
            labelWidth : 60,
            margin : "5, 0, 0, 0",
            xtype : "combo",
            queryMode : "local",
            editable : false,
            valueField : "id",
            store : Ext.create("Ext.data.ArrayStore", {
                fields : ["id", "text"],
                data : [[-1, "全部"], [0, "记应付账款"], [1, "现金付款"],
                    [2, "预付款"]]
            }),
            value : -1
        }, {
            xtype : "container",
            items : [{
                xtype : "button",
                text : "查询",
                width : 100,
                margin : "5 0 0 10",
                iconCls : "PSI-button-refresh",
                handler : me.onQuery,
                scope : me
            }, {
                xtype : "button",
                text : "清空查询条件",
                width : 100,
                margin : "5, 0, 0, 10",
                handler : me.onClearQuery,
                scope : me
            }]
        }];
    },
    /**
     * 刷新销售订单主表记录
     */
    refreshMainGrid : function(id) {
        var me = this;

        Ext.getCmp("rso_edit_pagingToobar").doRefresh();
        me.__lastId = id;
    },
});